package middleware

import (
	jsoniter "github.com/json-iterator/go"
	"github.com/labstack/echo"
)

type context struct {
	echo.Context
}

var json = jsoniter.ConfigCompatibleWithStandardLibrary

func Context() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(ctx echo.Context) error {
			return next(&context{ctx})
		}
	}
}

func (c *context) JSON(code int, i interface{}) (err error) {
	_, pretty := c.QueryParams()["pretty"]
	if pretty {
		return c.JSONPretty(code, i, "  ")
	}
	b, err := json.Marshal(i)
	if err != nil {
		return
	}
	return c.JSONBlob(code, b)
}

func (c *context) JSONPretty(code int, i interface{}, indent string) (err error) {
	b, err := json.MarshalIndent(i, "", indent)
	if err != nil {
		return
	}
	return c.JSONBlob(code, b)
}

func (c *context) JSONP(code int, callback string, i interface{}) (err error) {
	b, err := json.Marshal(i)
	if err != nil {
		return
	}
	return c.JSONPBlob(code, callback, b)
}
